#!/bin/bash

# CentOS 7 部署脚本
# 用于在CentOS 7环境中部署酒店管理系统

echo "开始在CentOS 7环境中部署酒店管理系统..."

# 检查是否以root权限运行
if [[ $EUID -eq 0 ]]; then
   echo "请不要以root用户运行此脚本"
   exit 1
fi

# 检查操作系统版本
echo "检查操作系统版本..."
if [[ -f /etc/redhat-release ]]; then
    OS_VERSION=$(cat /etc/redhat-release)
    echo "  操作系统: $OS_VERSION"
    if [[ $OS_VERSION != *"CentOS Linux release 7."* ]]; then
        echo "  警告: 此脚本专为CentOS 7设计，当前系统可能不完全兼容"
    fi
else
    echo "  警告: 无法确定操作系统版本，可能不是CentOS系统"
fi

# 检查Docker服务状态
echo "检查Docker服务..."
if ! command -v docker &> /dev/null; then
    echo "错误: 未找到Docker命令，请先安装Docker"
    echo "在CentOS 7中安装Docker的命令:"
    echo "  sudo yum install -y yum-utils device-mapper-persistent-data lvm2"
    echo "  sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo"
    echo "  sudo yum install -y docker-ce docker-ce-cli containerd.io"
    echo "  sudo systemctl start docker"
    echo "  sudo systemctl enable docker"
    exit 1
fi

if ! systemctl is-active --quiet docker; then
    echo "错误: Docker服务未运行，请先启动Docker服务"
    echo "启动Docker服务命令: sudo systemctl start docker"
    exit 1
fi

echo "  ✓ Docker服务正在运行"

# 检查Docker Compose
echo "检查Docker Compose..."
if ! command -v docker-compose &> /dev/null; then
    echo "错误: 未找到docker-compose命令，请先安装Docker Compose"
    echo "在CentOS 7中安装Docker Compose的命令:"
    echo "  sudo curl -L \"https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)\" -o /usr/local/bin/docker-compose"
    echo "  sudo chmod +x /usr/local/bin/docker-compose"
    echo "  sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose"
    exit 1
fi

echo "  ✓ Docker Compose已安装"

# 检查必要文件
echo "检查必要文件..."
REQUIRED_FILES=("docker-compose.yml" "Dockerfile" "app.py" "requirements.txt" "docker-init-db.py")
for FILE in "${REQUIRED_FILES[@]}"; do
    if [ -f "$FILE" ]; then
        echo "  ✓ $FILE 存在"
    else
        echo "  ✗ $FILE 不存在，请确保在正确的目录中运行此脚本"
        exit 1
    fi
done

# 检查端口占用
echo "检查端口占用情况..."
PORTS=(80 3306 5000)
for PORT in "${PORTS[@]}"; do
    if netstat -tlnp | grep -q ":$PORT "; then
        PROCESS=$(netstat -tlnp | grep ":$PORT " | awk '{print $7}')
        echo "  ! 警告: 端口 $PORT 已被占用 ($PROCESS)"
        echo "    建议停止占用该端口的进程或修改docker-compose.yml中的端口映射"
    else
        echo "  ✓ 端口 $PORT 未被占用"
    fi
done

# 停止并删除现有容器（如果存在）
echo "停止并清理现有容器..."
docker-compose down

# 构建并启动所有服务
echo "构建并启动服务..."
docker-compose up --build -d

# 等待服务启动
echo "等待服务启动（约30-60秒）..."
sleep 30

# 检查服务状态
echo "检查服务状态:"
docker-compose ps

echo ""
echo "部署完成！"
echo "========================="
echo "访问地址:"
echo "  前台: http://localhost"
echo "  管理后台: http://localhost/admin"
echo "  数据库: localhost:3306"
echo ""
echo "管理员账户:"
echo "  用户名: hyadmin"
echo "  密码: admin123"
echo ""
echo "如需查看日志，请执行: docker-compose logs"
echo "如需停止服务，请执行: docker-compose down"